package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.*;

@WebListener
public class OnlineListener implements HttpSessionAttributeListener {

    public static Map<String, Date> onlineUsers = new HashMap<>();

    public OnlineListener() {
    }

    @Override
    public void attributeAdded(HttpSessionBindingEvent sbe) {
        sbe.getName();//添加到会话的属性名
        sbe.getValue();//添加到会话中的属性值
        if (sbe.getName().equals("loginedUser")){
            onlineUsers.put((String) sbe.getSession().getAttribute("loginedUser"), new Date());
        }


    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        if(sbe.getValue().equals("loginedUser")){
            onlineUsers.remove(sbe.getValue().toString());
        }
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        /* This method is called when an attribute is replaced in a session. */
        if (sbe.getName().equals("loginedUser")){
            String oldname = (String) sbe.getValue();
            String newname = (String) sbe.getSession().getAttribute("loginedUser");
            //移除原来的名字
            onlineUsers.remove(oldname);
            //添加新的名字
            onlineUsers.put(newname, (Date) sbe.getSession().getAttribute("loginedTiome"));
        }
    }
}
